package com.app.exception;

import com.app.common.ResponseResult;
import com.app.enums.ResponseEnum;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

@ControllerAdvice
public class RuntimeExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseResult handle(RuntimeException e){
        return ResponseResult.error(ResponseEnum.ERROR,e.getMessage());
    }

    @ExceptionHandler(UserLoginException.class)
    @ResponseBody
    public ResponseResult userLoginHandle(){
        return ResponseResult.error(ResponseEnum.NEED_LOGIN);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult notValidExceptionHandler(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();

        Objects.requireNonNull(bindingResult.getFieldError());

        return ResponseResult.error(ResponseEnum.PARAM_ERROR,
                bindingResult.getFieldError().getField()+" "+bindingResult.getFieldError().getDefaultMessage());


    }
}
